<template>
  <div class="flex flex-col h-full">
    <searchContainer @search="getDetailData" @reset="() => formRef.resetFields()">
      <a-form ref="formRef" class="form-style-flex" :model="formState" :colon="false" :label-col="{ style: { width: '70px' } }">
        <a-form-item name="pyjm" class="w-1/5">
          <a-input v-model:value="formState.pyjm" placeholder="员工编号/员工姓名/助记码" />
        </a-form-item>
      </a-form>
    </searchContainer>
    <a-card class="mt-2 flex-1">
      <BaseTable
        :data-source="dataSource"
        column-code="000082"
        :loading="loading"
        max-fill
        :extra-height="64"
        :row-class-name="(record) => (record.isNew ? 'table-row-new' : '')"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'status'">
            <a-switch v-model:checked="record.status" checked-value="0" un-checked-value="1" @change="editRow(record)" />
          </template>
          <template v-if="column.dataIndex === 'empName'">
            <EditCell title="药品名称">
              <SelectTable v-model:value="record.empName" type="员工" placeholder="请输入" @select="onSelectNurse($event, record)" />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'discountPercent'">
            <EditCell title="最高折扣率(%)">
              <a-input v-model:value="record.discountPercent" v-input:float.2 placeholder="请输入" @blur="onCellBlur(record)" />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'maxDiscountAmount'">
            <EditCell title="最高减免金额">
              <a-input v-model:value="record.maxDiscountAmount" v-input:float.2 placeholder="请输入" @blur="onCellBlur(record)" />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <BaseButton confirm-text="确认删除？" type="text" danger size="small" @click="onDelete(record)">移除</BaseButton>
          </template>
        </template>
        <template #footer>
          <div class="text-center sticky bottom-0">
            <a-button class="mr-2" :disabled="formState?.id" type="primary" ghost @click="addRow()"> 新增一行 </a-button>
            <a-button type="primary" :disabled="dataSource.length === 0" @click="saveNewRows()"> 保存 </a-button>
          </div>
        </template>
      </BaseTable>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'
import searchContainer from '@/components/SearchContainer'

const dataSource = ref([{ isNew: true }])
const loading = ref(false)
const formRef = ref(null)
const formState = ref({})
const editRow = (row) => !row.isNew && fetchSave(row)
const fetchSave = async (row) => {
  const { code, msg } = await post('/operation/opex/doSaveDiscountPermisson', { ...row })
  if (code !== 0) return message.error(msg || '操作失败')
  getDetailData()
  message.destroy()
  message.success(row.isNew ? '新增成功' : '修改成功')
}
const onSelectNurse = (medicine, row) => {
  row.empName = medicine?.empName
  row.sex = medicine?.sex
  row.age = medicine?.age
  row.phone = medicine?.phone
  row.empId = medicine?.empId
  row.deptName = medicine?.bmmc
  row.ksmc = medicine?.ksmc
  row.categoryName = medicine?.emplb
  editRow(row)
}

//添加行
const addRow = async () => {
  const key = `row-${dataSource.value.length}`
  const addRow = { key, isNew: true }
  dataSource.value.push(addRow)
}

const onDelete = async (row) => {
  if (row.isNew) {
    dataSource.value = dataSource.value.filter((item) => item.key !== row.key)
  } else {
    const { code, msg } = await post('/operation/opex/doDelDiscountPermisson', { id: row.id })
    code === 0 ? getDetailData() : message.error(msg || '删除失败')
  }
}

const saveNewRows = async () => {
  const newRow = dataSource.value.filter((item) => item.isNew)
  if (newRow.length === 0) return message.error('没有新增的数据')
  newRow.forEach((item) => {
    if (item.empName && (item.discountPercent || item.discountPercent === 0) && (item.maxDiscountAmount || item.maxDiscountAmount === 0)) {
      fetchSave(item)
    } else {
      message.destroy()
      message.error('请填写完整信息')
    }
  })
}

const getDetailData = async () => {
  loading.value = true
  const { data, code, msg } = await post('/operation/opex/getDiscountPermissonList', {
    pyjm: formState.value.pyjm
  })
  if (code !== 0) return message.error(msg)
  loading.value = false
  if (code === 0) {
    dataSource.value = data
    dataSource.value = data.map((item) => {
      item.status = item.status ? '1' : '0'
      return item
    })
  }
}

const onCellBlur = (row) => {
  if (row.discountPercent && !isNaN(row.discountPercent)) {
    row.discountPercent = Math.min(row.discountPercent, 100) // 如果输入的数字大于100，将其设置为100
  } else {
    row.discountPercent = 0 // 如果输入的不是有效数字，则清空输入框的值
  }
  if (!row.maxDiscountAmount || row.maxDiscountAmount < 0) row.maxDiscountAmount = 0
  if (row.empName && (row.discountPercent || row.discountPercent === 0) && (row.maxDiscountAmount || row.maxDiscountAmount === 0)) {
    row.id && editRow(row)
  } else {
    message.destroy()
    message.error('请填写完整信息')
  }
}

onMounted(() => {
  getDetailData()
})
</script>
<style lang="less" scoped>
.ant-picker {
  width: 100%;
}
</style>
